package com.lighting.smssystem.controller;

import com.alibaba.fastjson.JSONObject;
import com.lighting.smssystem.aspect.RequireRole;
import com.lighting.smssystem.constrants.UserRole;
import com.lighting.smssystem.model.Metric;
import com.lighting.smssystem.model.Template;
import com.lighting.smssystem.model.User;
import com.lighting.smssystem.model.vo.PromateEntity;
import com.lighting.smssystem.service.impl.MiaodiyunSmsServiceImpl;
import com.lighting.smssystem.service.impl.TemplateService;
import com.lighting.smssystem.service.impl.UserService;
import com.lighting.smssystem.utils.BaseResponse;
import com.lighting.smssystem.utils.JWTUtils;
import com.lighting.smssystem.utils.ResponseUtil;
import com.lighting.smssystem.utils.SmsResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Authorization;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;

/**
 * Author LeeMaster
 *
 * 修改密码，修改账户中文名，修改账户绑定手机号,完善信息
 */
@Api(
        value = "用户接口",
        protocols = "http",
        description = "就一个接口，修改一个字段后，全字段返回，直接保存"
)
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    private String path = System.getProperty("user.dir") + "/upfile/";

    @Autowired
    private UserService userService;

    @Autowired
    private MiaodiyunSmsServiceImpl miaodiyunSmsService;

    @Autowired
    private TemplateService templateService;

    @ApiOperation(
            value = "修改用户信息，密码，完善各种信息",
            httpMethod = "PUT",
            authorizations = @Authorization(
                    "无需鉴权"
            )

    )
    @PutMapping("/account")
    public BaseResponse updateUser(
            @ApiParam(name = "用户信息",type = "json") @RequestBody User user
            ){
        log.info("修改用户信息{}", user.toString());
        return ResponseUtil.success(userService.updateUser(user));
    }


    @ApiOperation(
            value = "获取用户用量信息",
            httpMethod = "GET",
            authorizations = @Authorization(
                    "VIP 用户"
            )

    )
    @GetMapping("/metric")
    @RequireRole(role = {UserRole.VIP,UserRole.ADMIN})
    public BaseResponse getMetric(
            @ApiParam @RequestParam("id") long id
    ){
        log.info("获取用户用量Id:{}", id);
        return ResponseUtil.success(userService.metric(id));
    }


    @ApiOperation(
            value = "发送营销短信",
            httpMethod = "POST",
            authorizations = @Authorization(
                    "VIP 用户"
            )

    )
    @PostMapping("/promate")
    @RequireRole(role = UserRole.VIP)
    public BaseResponse sendMessage(
            @ApiParam  @RequestBody PromateEntity entity,
            HttpServletRequest request
            ){
        log.info("发送营销短信{}", entity.toString());
        String token = request.getHeader("X-token");
        User user = JWTUtils.parseJwt(token);
        int status = userService.reduceMeric(user.getUserId(), entity.getPhones().size());
        if (status == -2) {
            return ResponseUtil.failed(504, "单次发送的短信条数超过限制，请联系管理员增加");
        }
        if (status == -1) {
            return ResponseUtil.failed(504, "短信条数不足，请联系管理员充值");
        }
        SmsResponse smsResponse = miaodiyunSmsService.sendMsg(templateService.queryById(entity.getTemplateId()), entity.getPhones(), entity.getParams());
        if (smsResponse.getRespCode().equals("0000")) {
            return ResponseUtil.success(smsResponse.getRespDesc());
        }
        return ResponseUtil.failed(400, smsResponse.getRespDesc());
//        return ResponseUtil.success();
    }

    @PostMapping(value = "/upfile")
    @RequireRole(role = UserRole.VIP)
    @ResponseBody
    public BaseResponse upFile(@RequestParam("file") MultipartFile file) throws IOException {
        String name = file.getOriginalFilename();
        File file1 = new File(path + name);
        if (!file1.getParentFile().exists()) {
            try {
                file1.getParentFile().mkdirs();
                file1.createNewFile();
            } catch (IOException io) {
                System.out.println(io);
                io.printStackTrace();
            }
        }
        OutputStream outputStream = new FileOutputStream(file1);
        IOUtils.copy(file.getInputStream(), outputStream);
        JSONObject jsonObject = new JSONObject();
        InetAddress addr = InetAddress.getLocalHost();
        String ip=addr.getHostAddress().toString();
        jsonObject.put("src", "http://" + ip + ":8000/sms/user/image/file/" + name);
        return ResponseUtil.success(jsonObject);
    }

    @RequireRole(role = UserRole.VIP)
    @RequestMapping(value = "/image/file/{name}", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<Resource> preview(@PathVariable("name") String name) throws IOException {
        InputStream inputStream = new FileInputStream(new File(path + name));
        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
        HttpHeaders httpHeaders = new HttpHeaders();
        return new ResponseEntity<>(inputStreamResource, httpHeaders, HttpStatus.OK);
    }

}
